package service

import (
	"admin100/app/model"
	"admin100/app/model/commonmodel/userEnum"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"admin100/library/utils/enum"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/util/gconv"
)

var Middle = &MiddleService{}

type MiddleService struct {
}

func (s *MiddleService) Ctx(r *ghttp.Request) {
	customCtx := model.Context{
		Session: r.Session,
	}
	Context.Init(r, &customCtx)
	if user := Session.GetUser(r.Context()); user != nil {
		//如果有需要后期可以重定义userContext中的user为ContextUser来减少字段
		customCtx.User = user
	}

}

// 帐号在其他地方登录
func (s *MiddleService) IsDifferentLogin(r *ghttp.Request) {

	if g.Cfg().GetBool(enum.CfgIsAllowMultipleLogin, false) {
		//allow
		r.Middleware.Next()
		return
	}

	//帐号在其他地方登录
	ctxContext := Context.Get(r.Context())
	if ctxContext != nil && ctxContext.User != nil && ctxContext.User.Id > 0 {
		var sessionKey = enum.CacheUser + gconv.String(ctxContext.User.Id)
		cacheIdVar, err := gcache.GetVar(sessionKey)

		defErr.IfPanic(err, define.DataOptFail)
		if cacheIdVar.IsEmpty() {
			gcache.Set(sessionKey, r.Session.Id(), 0)
		} else {
			//judge
			if cacheIdVar.String() != r.Session.Id() {
				defErr.Panic(define.DifferentLogin)
			}
		}
	}
	r.Middleware.Next()
}

// check帐户
func (s *MiddleService) Auth(r *ghttp.Request) {
	ctxContext := Context.Get(r.Context())
	if ctxContext != nil && ctxContext.User != nil && ctxContext.User.Id > 0 {
		if ctxContext.User.Status != userEnum.Enabled {
			defErr.Panic(define.UserForbidden)
		}
	} else {
		defErr.Panic(define.UserExpire)
	}

	r.Middleware.Next()
}
